package gncom.qr;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class WebViewerPage extends Activity {

	private WebView QR_webView;

	private SQLiteDatabase mDatabase;

	private LinearLayout webViewerLayout;

	private String webTitle;

	private void openData() {
		mDatabase = openOrCreateDatabase("storyInfo",
				SQLiteDatabase.CREATE_IF_NECESSARY, null);
		Cursor c_sqlite_master = mDatabase.rawQuery(
				"select name from sqlite_master where type=? and name=?",
				new String[] { "table", "categoryNames" });
		startManagingCursor(c_sqlite_master);
		if (c_sqlite_master.getCount() == 0) {
			mDatabase
					.execSQL("create table categoryNames(c_id integer primary key autoincrement, name text);");
			ContentValues values = new ContentValues();
			values.put("name", "카테고리추가");
			mDatabase.insert("categoryNames", null, values);
			values.put("name", "기타...");
			mDatabase.insert("categoryNames", null, values);
		}
	}

	public ArrayList<String> getCategoryList() {

		ArrayList<String> list = new ArrayList<String>();

		Cursor c_categoryNames = mDatabase.query("categoryNames", null, null,
				null, null, null, "c_id asc");
		startManagingCursor(c_categoryNames);
		c_categoryNames.moveToFirst();
		while (!(c_categoryNames.isAfterLast())) {
			list.add(c_categoryNames.getString(c_categoryNames
					.getColumnIndex("name")));
			c_categoryNames.moveToNext();
		}

		return list;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webviewer_page);

		openData();

		webViewerLayout = (LinearLayout) findViewById(R.id.webViewerLayout);

		QR_webView = (WebView) findViewById(R.id.QR_webView);

		String url = getIntent().getStringExtra("url");

		QR_webView.getSettings().setJavaScriptEnabled(true);

		QR_webView.loadUrl(url);

		webTitle = getWebTitle(url);

		System.out.println(webTitle);

		QR_webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return super.shouldOverrideUrlLoading(view, url);
			}
		});

	}// end onCreate()

	public String getWebTitle(String url) {
		StringBuffer StringBuffer_Data = new StringBuffer();
		URL mUrl = null;
		HttpURLConnection conn = null;
		String charset = null;
		try {
			mUrl = new URL(url);

			conn = (HttpURLConnection) mUrl.openConnection();

			System.out
					.println("conn.getContentType>>>" + conn.getContentType());
			charset = conn.getContentType().substring(
					conn.getContentType().indexOf("=") + 1);
			System.out.println("charset = " + charset);

			
			
			InputStream InputStream_html = mUrl.openStream();
			BufferedReader BufferedReader_input = new BufferedReader(
					new InputStreamReader(InputStream_html,charset), 1024);
			while (true) {
				String String_line = BufferedReader_input.readLine();
				if (String_line == null) {
					break;
				}
				StringBuffer_Data.append(String_line).append("\n");
			}
		} catch (IOException e) {
			Log.e("qrstory", "StringBuffer_Data.append error");
			return "";
		}


		String result = StringBuffer_Data.toString().substring(
				StringBuffer_Data.toString().indexOf("<title>") + 7,
				StringBuffer_Data.toString().indexOf("</title>"));
		
		System.out.println("result >> "+result);
//		if (!(charset.equalsIgnoreCase("UTF-8"))) {
//			try {
//				result = new String(result.getBytes("MS949"), "UTF-8");
//				System.out.println("title encoding after >> "+result);
//			} catch (UnsupportedEncodingException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
		
				
		
		return result;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			removeDialog(LIST_CATEGORY);
			showDialog(LIST_CATEGORY);

			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void qrImgUpdate(String lastId) {
		// ///// 인식결과 url 과 바코드 이미지전송.
		String profileImageBase64 = "";
		Bitmap resized = null;
		URL imgSrc = null;
		InputStream is = null;
		webViewerLayout.buildDrawingCache();
		Bitmap captureView = webViewerLayout.getDrawingCache();
		resized = Bitmap.createScaledBitmap(captureView, 50, 82, true);
		try {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			resized.compress(CompressFormat.PNG, 100, outStream);
			byte[] image = outStream.toByteArray();
			profileImageBase64 = Base64.encodeToString(image, 0);
		} catch (Exception e) {
			Log.e("getQRCodeBase64_err", e.getMessage());
		}

		ContentValues values = new ContentValues();
		values.put("qrcode", profileImageBase64);
		mDatabase.update("qrStory", values, "id=?", new String[] { lastId });
	}

	//
	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// menu.add(0, 1, 0, "카테고리 등록");
	//
	// return true;
	// }
	//
	// @Override
	// public boolean onOptionsItemSelected(MenuItem item) {
	// switch (item.getItemId()) {
	// case 1:
	// showDialog(0);
	//
	// break;
	//
	// }
	// return true;
	// }
	private static final int INSERT_CATEGORY = 4;
	private static final int LIST_CATEGORY = 5;

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case LIST_CATEGORY:
			LayoutInflater inflater = LayoutInflater.from(this);
			final View v = inflater.inflate(R.layout.alert_dialog_category,
					null);
			ListView alertCategoryList = (ListView) v
					.findViewById(R.id.alert_category_list);
			ArrayList<String> category_list = new ArrayList<String>();
			category_list = getCategoryList();
			alertCategoryList.setAdapter(new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, category_list));
			alertCategoryList.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View v,
						int position, long id) {

					if (((TextView) v).getText().equals("카테고리추가")) {

						LayoutInflater factory = LayoutInflater
								.from(getApplicationContext());
						final View textEntryView = factory.inflate(
								R.layout.alert_up_del, null);
						final EditText category_edit = (EditText) textEntryView
								.findViewById(R.id.category_edit);
						new AlertDialog.Builder(WebViewerPage.this)
								.setIcon(R.drawable.alert_dialog_icon)
								.setTitle("카테고리 생성")
								.setView(textEntryView)
								.setPositiveButton("생성",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {
												ContentValues values = new ContentValues();
												values.put("name",
														category_edit.getText()
																.toString());
												mDatabase.insert(
														"categoryNames", null,
														values);
												removeDialog(LIST_CATEGORY);
												showDialog(LIST_CATEGORY);

											}
										})
								.setNegativeButton("취소",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int whichButton) {

											}
										}).show();
						// Toast.makeText(getApplicationContext(),
						// ((TextView)v).getText(), 0).show();
						// Intent intent = new Intent(getApplicationContext(),
						// StoryPage.class);
						// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						// startActivity(intent);
						// finish();
					} else {
						ContentValues values_categoryName = new ContentValues();
						values_categoryName.put("categoryName", ((TextView) v)
								.getText().toString());
						
						Cursor c_qrStory = mDatabase.query("qrStory", null,
								null, null, null, null, "id desc");
						startManagingCursor(c_qrStory);
						c_qrStory.moveToFirst();
						String lastId = c_qrStory.getString(c_qrStory
								.getColumnIndex("id"));

						// c.moveToLast();
						// String firstId = c.getString(c.getColumnIndex("id"));

						Log.i("story", "lastId....." + lastId);
						Log.i("story", "webTitle....." + webTitle);
						
						mDatabase.update("qrStory", values_categoryName, "id=?",
								new String[] { lastId });

						// /////webTitle update
						ContentValues values_qrStory = new ContentValues();
						values_qrStory.put("webTitle", webTitle);
						mDatabase.update("qrStory", values_qrStory, "id=?",
								new String[] { lastId });

						// //////image update
						qrImgUpdate(lastId);

						Toast.makeText(
								getApplicationContext(),
								((TextView) v).getText()
										+ " 카테고리에 추가되었습니다.\n스토리를 작성하세요.", 0)
								.show();

						Intent intent = new Intent(getApplicationContext(),
								StoryWritePage.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						intent.putExtra("id", Integer.parseInt(lastId));
						intent.putExtra("position", 0);
						startActivity(intent);
						finish();
					}

				}
			});
			return new AlertDialog.Builder(this).setView(v).create();

		}
		return super.onCreateDialog(id);
	}

}